<template>
  <div class="ticket-box">
    <div class="header">
      <i v-if="showBack" class="el-icon-back back-btn" @click="$emit('back')"></i>
      {{ticket.ticketId?'编辑工单':'添加工单'}}
    </div>
    <div class="form">
      <el-form ref="ticketForm" class="el-form-diy" :rules="rules" :model="ticket">
        <el-form-item label="联系人名称" class="half" prop="customerName">
          <el-input @input="manualInput" v-model="ticket.customerName">
          </el-input>
          <div class="search" @click="$refs.searchGlobal.show()">
            <i class="el-icon-search"></i>
          </div>
          <div class="new-customer" v-if="showNewCustomerTip">新的联系人名称{{ticket.customerName}}将会创建</div>
        </el-form-item>
        <el-form-item label="联系人邮箱" class="half" prop="customerEmail">
          <el-input @input="manualInput" v-model="ticket.customerEmail"></el-input>
          <div class="new-customer" v-if="showNewCustomerTip">对于邮箱<{{ticket.customerEmail}}>，新的联系人{{ticket.customerName}}将自动创建</div>
        </el-form-item>
        <el-form-item label="联系人电话" class="half">
          <el-input v-model="ticket.customerMobile"></el-input>
        </el-form-item>
        <el-form-item label="主题" class="full" prop="title">
          <el-input v-model="ticket.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" class="full">
          <quill-editor style="margin-top: 40px" ref="text" v-model="ticket.content" :options="editorOption" />
        </el-form-item>
        <el-form-item label="状态" class="half" prop="status">
          <el-select v-model="ticket.status" style="width: 100%">
            <el-option value="open" label="Open"></el-option>
            <el-option value="closed" label="Closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单分配" class="half" prop="assigneeName">
          <el-input v-model="ticket.assigneeName"></el-input>
          <div @click="$refs.searchGlobal.show('people')" style="background: transparent;cursor: pointer;position: absolute;width: 100%;height: 40px;bottom: 0"></div>
        </el-form-item>
        <el-form-item label="优先级" class="half" prop="priority">
          <el-select v-model="ticket.priority" style="width: 100%">
            <el-option :value="1" label="低"></el-option>
            <el-option :value="2" label="中"></el-option>
            <el-option :value="3" label="高"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最终方案" class="full" prop="finalReply">
          <el-input v-model="ticket.finalReply"></el-input>
        </el-form-item>
        <div style="padding: 25px;margin-bottom: 50px;">
          <el-button type="primary" @click="submit">{{ticket.ticketId?'保存':'提交'}}</el-button>
          <el-button @click="$emit('cancel')">取消</el-button>
        </div>
      </el-form>
    </div>
    <SearchGlobal @select="globalSelect" ref="searchGlobal"></SearchGlobal>
  </div>
</template>

<script>
import {findById,saveTicket} from "@/api/ticket";
import { quillEditor } from 'vue-quill-editor'
import {isEmail} from "@/libs/util";
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import EditorConfig from '@/config/editor'

import SearchGlobal from '@/components/common/zsh-search-global'
export default {
  name: "ticket-edit-form",
  components: {
    quillEditor,
    SearchGlobal
  },
  props: {
    ticket: {
      type: Object,
      default() {
        return {priority:2, status:'open'}
      }
    },
    showBack:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editorOption: EditorConfig.editorOption,
      rules: {
        customerName: [
          {required: true, message: '请输入联系人名称', trigger: 'change'}
        ],
        customerEmail:[
          {required: true, message: '请输入联系人邮箱', trigger: 'change'},
          {validator: checkEmail, trigger: 'change'}
        ],
        title: [
          {required: true, message: '请输入工单主题', trigger: 'change'}
        ],
        status: [
          {required: true, message: '请选择工单状态', trigger: 'change'}
        ],
        assigneeName: [
          {required: true, message: '请选择工单所有者', trigger: 'change'}
        ]
      },
      isNewCustomer:false
    }
  },
  methods: {
    //对于手动输入，将自动创建联系人
    manualInput(e) {
      if(e) {
        this.isNewCustomer = true
      }else {
        this.isNewCustomer = false
      }
    },
    loadData() {
      let ticketId = this.$route.query['ticketId']
      this.ticket.ticketId = ticketId
      if(ticketId) {
        findById(ticketId).then(res => {
          if(res.code == 200) {
            if(res.data!=null) {
              this.ticket = res.data
            }else {
              this.$message.warning('工单不存在')
              setTimeout(() => {
                this.$router.replace({name:'ticket-all'})
              },1000)
            }
          }
        })
      }
    },
    globalSelect(mode,item) {
      if(mode == 'customer') {
        this.isNewCustomer = false
        console.log(item)
        this.ticket.customerId = item.customerId
        this.$set(this.ticket,'customerName', item.name)
        this.$set(this.ticket,'customerMobile', item.mobile)
        this.$set(this.ticket,'customerEmail', item.email)
        this.$emit('selectCustomer',item)
        return
      }
      if(mode == 'people') {
        if(item.hasOwnProperty('userId')) {
          this.ticket.assignee = 'user_'+item.userId
          this.$set(this.ticket,'assigneeName', item.nickname)
        }else {
          this.ticket.assignee = 'dept_'+item.deptId
          this.$set(this.ticket,'assigneeName', item.name + ' (组)')
        }
        return
      }
    },
    submit() {
      this.$refs['ticketForm'].validate((valid) => {
        if (valid) {
          saveTicket(this.ticket).then(res => {
            if(res.code == 200) {
              this.$message.success(this.ticket.ticketId?'保存成功':'添加成功')
              this.$emit('submitSuccess')
            }
          })
        } else {
          return false;
        }
      })
    }
  },
  computed:{
    showNewCustomerTip() {
      let ticket = this.ticket
      return isEmail(ticket.customerEmail) && ticket.customerName && ticket.customerName.trim() != '' && this.isNewCustomer
    }
  }
}


var checkEmail = (rule, value, callback) => {
  const mailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
  if (!value) {
    return callback(new Error('邮箱不能为空'))
  }
  setTimeout(() => {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的邮箱格式'))
    }
  }, 100)
}

</script>

<style scoped lang="less">
.ticket-box {
  flex: 1;
  box-shadow: #cdcdcd -5px 0 5px -3px;
  border-right: 1px solid #F0F0F0;
  padding: 0 30px;
  overflow: hidden;
  overflow-y: auto;
  .header {
    height: 80px;
    line-height: 80px;
    font-size: 20px;

    .back-btn {
      cursor: pointer;
      &:hover {
        color: #0091ff;
      }
    }
  }
  .form {
    .el-form-diy {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      .new-customer {
        position: absolute;
        bottom: -30px;
        color: #666666;
        font-size: 12px;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .search {
        position: absolute;
        bottom: 0;
        right: 0px;
        color: #666666;
        cursor: pointer;
        padding: 0 10px;
        &:hover {
          color: #0091ff;
        }
      }
    }
  }
}

/deep/ .ql-snow .ql-picker-label::before {
  vertical-align: top;
}

/deep/ .ql-snow .ql-picker.ql-size {
  width: 78px !important;
}

/deep/ .ql-toolbar.ql-snow .ql-formats {
  margin-right: 0;
}

/deep/ .ql-snow * {
  vertical-align: top !important;
}
/deep/ .ql-toolbar.ql-snow {
  padding-bottom: 0;
}
/deep/ .ql-editor {
  height: 250px;
}
</style>
